import os
from csv import DictReader

# Define order of migrations
MIGRATION_TASKS = [
    'FD_GROUP', 'DERIV_CD', 'SRC_CD', 'DATA_SRC', 'NUTR_DEF',
    'NUT_DATA', 'WEIGHT', 'FOOTNOTE', 'DATSRCLN', 'FOOD_DES', 
]

FORM_DICT = {
    'DATA_SRC': {
        'form_name': 'DataSourceForm',
        'fieldnames': [
            'datasrc_id', 'authors', 'title', 'year', 'journal', 'vol_city',
            'issue_state', 'start_page', 'end_page'
        ],
    },
    'DATSRCLN': {
        'form_name': 'DataSourceLinkForm',
        'fieldnames': ['ndb_no', 'nutr_no', 'datasrc_id'],
    },
    'DERIV_CD': {
        'form_name': 'DataDerivationForm',
        'fieldnames': ['deriv_cd', 'deriv_desc'],
    },
    'FD_GROUP': {
        'form_name': 'FoodGroupForm',
        'fieldnames': ['fdgrp_cd', 'fdgrp_desc'],
    },
    'FOOD_DES': {
        'form_name': 'FoodDescriptionForm',
        'fieldnames': [
            'ndb_no', 'fdgrp_cd', 'long_desc', 'shrt_desc', 'comname',
            'manufacname', 'survey', 'ref_desc', 'refuse', 'sciname',
            'n_factor', 'pro_factor', 'fat_factor', 'cho_factor'
        ],
    },
    'FOOTNOTE': {
        'form_name': 'FootnoteForm',
        'fieldnames': [
            'ndb_no', 'footnt_no', 'footnt_typ', 'nutr_no', 'footnt_txt'
        ],
    },
    'NUT_DATA': {
        'form_name': 'NutrientDataForm',
        'fieldnames': [
            'ndb_no', 'nutr_no', 'nutr_val', 'num_data_pts', 'std_error',
            'src_cd', 'deriv_cd', 'ref_ndb_no', 'add_nutr_mark', 'num_studies',
            'min', 'max', 'df', 'low_eb', 'up_eb', 'stat_cmt', 'cc'
        ],
    },
    'NUTR_DEF': {
        'form_name': 'NutrientDefinitionForm',
        'fieldnames': [
            'nutr_no', 'units', 'tagname', 'tagnames', 'num_dec', 'sr_order'
        ],
    },
    'SRC_CD'  : {
        'form_name': 'SourceCodeForm',
        'fieldnames': ['src_cd', 'srccd_desc'],
    },
    'WEIGHT'  : {
        'form_name': 'WeightForm',
        'fieldnames': [
            'ndb_no', 'seq', 'amount', 'msre_desc', 'gm_wgt', 'num_data_pts',
            'std_dev'
        ],
    },
}

class ARSReader:
    """
    A CSV reader which will iterate over lines in given file ``f``, which
    should be one of the 10 ASCII nutritional data files from the
    `USDA National Nutrient Database for Standard Reference` dataset, which
    can be obtained here:
    
        http://www.ars.usda.gov/Services/docs.htm?docid=17478
    """
    
    def __init__(self, file_name, fieldnames, encoding='latin-1', start=0, end=None, **kwargs):
        self.reader   = DictReader(open(file_name, "r"), fieldnames, delimiter="^", quotechar='~', **kwargs)
        self.encoding = encoding
        try:
            self.start = int(start)
        except TypeError:
            self.start = 0
        try:
            self.end = int(end)
        except TypeError:
            self.end = None
    
    def next(self):
        while self.reader.reader.line_num < self.start:
            self.reader.next()
        if self.end and self.reader.reader.line_num >= self.end:
            raise StopIteration
        row = self.reader.next()
        for k,v in row.items():
            row[k] = unicode(v.rstrip('~').lstrip('~'), self.encoding)
        return row
    
    def count(self):
        return sum(1 for row in self)
    
    def __iter__(self):
        return self

def dynamic_import(name):
    '''This function allows you to dynamically import a module given a string
        corresponding to it's normal import command.
        
        e.g. Nutrition app's forms
            >>> dynamic_import('nutrition.forms')
    '''
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod